package org.itboys.weixin.tools;

import java.util.Date;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.encode.CodeUtils;
import org.itboys.commons.utils.json.JsonUtils;
import org.itboys.weixin.constant.WeixinConstants;
import org.itboys.weixin.dto.WeixinUserInfo;
import org.itboys.weixin.dto.WeixinUserList;
import org.itboys.weixin.entity.WeixinUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 微信用户操作相关
 * @author ChenJunhui
 *
 */
public class WeixinUserUtils {
	
	private static  Logger logger = LoggerFactory.getLogger(WeixinUserUtils.class);
	
	/**
	 * 获取用户列表
	 * @param appId
	 * @param appSecret
	 * @param nextOpenId
	 * @return
	 */
	public static WeixinUserList getWeixinUserList(String appId,String appSecret,String nextOpenId){
		String accessToken = WeixinUtils.getAccessToken(appId, appSecret);
		String url = StringUtils.isBlank(nextOpenId)?WeixinConstants.URL.GET_USER_LIST:WeixinConstants.URL.GET_USER_LIST+nextOpenId;
		PostMethod postMethod = new PostMethod(url.replace("{0}", accessToken));
		try{
			 HttpClient httpclient = HttpHelper.getHttpClient();
			 int statusCode = httpclient.executeMethod(postMethod);
			 if (statusCode != HttpStatus.SC_OK) {
		    	 logger.error("getWeixinUserList error statusCode={}",statusCode);
		    	 return null;
		    }
			String userListJson  = postMethod.getResponseBodyAsString();
			WeixinUserList userList = JsonUtils.jsonToObject(WeixinUserList.class, userListJson);
			return userList;
		}catch(Exception e){
			logger.error("getWeixinUserList EXCEPTION",e);
			return null;
		}finally{
			if(postMethod!=null){
				postMethod.releaseConnection();
			}
		}
	}
	
	/**
	 * 获取微信用户对象
	 * @param appId
	 * @param appSecret
	 * @param userId
	 * @return
	 */
	public static WeixinUser getWeixinUser(String appId,String appSecret,String userId){
		WeixinUserInfo userInfo = getWeixinUserInfo(appId, appSecret, userId);
		WeixinUser user = new WeixinUser();
		user.setCity(userInfo.getCity());
		user.setCountry(user.getCountry());
		user.setHeadimgurl(userInfo.getHeadimgurl());
		user.setNickname(userInfo.getNickname());
		user.setOpenid(userId);
		user.setProvince(userInfo.getProvince());
		user.setSex(userInfo.getSex());
		user.setStatus(1);
		user.setSubscribe(userInfo.getSubscribe());
		user.setSubscribeTime(new Date());
		return user;
	}
	
	/**
	 * 获取微信用户对象
	 * @param appId
	 * @param appSecret
	 * @param userId
	 * @return
	 */
	public static WeixinUser getWeixinUser(String appId,String appSecret,String userId, Long weixinId){
		WeixinUserInfo userInfo = getWeixinUserInfo(appId, appSecret, userId);
		WeixinUser user = new WeixinUser();
		user.setCity(userInfo.getCity());
		user.setCountry(user.getCountry());
		user.setHeadimgurl(userInfo.getHeadimgurl());
		user.setNickname(userInfo.getNickname());
		user.setOpenid(userId);
		user.setProvince(userInfo.getProvince());
		user.setSex(userInfo.getSex());
		user.setStatus(1);
		user.setSubscribe(userInfo.getSubscribe());
		user.setSubscribeTime(new Date());
		user.setWeixinId(weixinId);
		return user;
	}

	/**
	 * 获取微信用户的信息
	 * @param accessToken
	 * @param userId
	 * @return
	 */
	public static WeixinUserInfo getWeixinUserInfo(String appId,String appSecret,String userId){
		String accessToken = WeixinUtils.getAccessToken(appId, appSecret);
		String userInfoStr = getWeixinUserStr(accessToken,userId);
		WeixinUserInfo userInfo = JsonUtils.jsonToObject(WeixinUserInfo.class, userInfoStr);
		userInfo.setNickname(CodeUtils.changeRequestEncode(userInfo.getNickname(), CommonConstants.ENCODE.ISO_8859_1, CommonConstants.ENCODE.UTF_8));
		userInfo.setProvince(CodeUtils.changeRequestEncode(userInfo.getProvince(), CommonConstants.ENCODE.ISO_8859_1, CommonConstants.ENCODE.UTF_8));
		userInfo.setCountry(CodeUtils.changeRequestEncode(userInfo.getCountry(), CommonConstants.ENCODE.ISO_8859_1, CommonConstants.ENCODE.UTF_8));
		userInfo.setCity(CodeUtils.changeRequestEncode(userInfo.getCity(), CommonConstants.ENCODE.ISO_8859_1, CommonConstants.ENCODE.UTF_8));
		return userInfo;
	}
	
	private static String getWeixinUserStr(String accessToken,String userId){
		PostMethod postMethod = new PostMethod(WeixinConstants.URL.GET_USER_INFO_URL.replace("{0}", userId).replace("{1}", accessToken));
		try{
			 HttpClient httpclient = HttpHelper.getHttpClient();
			 int statusCode = httpclient.executeMethod(postMethod);
			 if (statusCode != HttpStatus.SC_OK) {
		    	 logger.error("getWeixinUserInfo error accessToken={} userId={}",accessToken,userId);
		    	 return String.valueOf(statusCode);
		    }
			String userInfoStr = postMethod.getResponseBodyAsString();
			return userInfoStr;
		}catch(Exception e){
			return CommonConstants.FAIL;
		}finally{
			if(postMethod!=null){
				postMethod.releaseConnection();
			}
		}
	}
	
}
